<?php
class Orm{
	// 请求百度ORM url
	protected $url = 'https://aip.baidubce.com/oauth/2.0/token?';
	// client_id
	protected $client_id = '2G7pzliIAXGcfICwWMKXWDXx';
	// client_secret
	protected $client_secret = 'sNhg1vOvGwQfLnfVFOn5sqkuBGTG1EZs';

	/*
	* 获取百度ORM token
	*/
	public function getOrmToken()
	{
		// 请求参数
		$post_data['grant_type'] = 'client_credentials';
		$post_data['client_id'] = $this->client_id;
		$post_data['client_secret'] = $this->client_secret;
		
		// 官方建议使用POST 这里测试使用get 演示的话没有封装一系列的请求等
		$url = $this->url.http_build_query($post_data);
		$content = file_get_contents($url);
		if (!$content) return ['code'=>0,'data'=>[],'msg'=>'请求有误'];
		$accessArr = json_decode($content,1);
		if (isset($accessArr['error'])) return ['code'=>0,'data'=>[],'msg'=>$accessArr['error_description']];
		
		// 得到 token 及会话过期时间后 这里应当使用 Cache or 持久化存储 方便后期调用 且会话过期后 重新调用该fuc 这里目前先不做演示
		return  ['code'=>1,'data'=>$accessArr,'msg'=>'调用成功'];
	}


	public function request_post($postUrl = '', $param = [])
	{
	    if (empty($postUrl) || empty($param)) {
	        return false;
	    }
	
	    $curlPost = $param;
	    $header =  array(
          'Content-Type:'.'application/x-www-form-urlencoded'
      	);
	    // 初始化curl
	    $curl = curl_init();
	    curl_setopt($curl, CURLOPT_URL, $postUrl);
	    curl_setopt($curl, CURLOPT_HTTPHEADER, $header);
	    curl_setopt($curl, CURLOPT_HEADER, 0);
	    // 要求结果为字符串且输出到屏幕上
	    curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
	    curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
	    // post提交方式
	    curl_setopt($curl, CURLOPT_POST, 1);
	    curl_setopt($curl, CURLOPT_POSTFIELDS,  http_build_query ( $curlPost ));
	    curl_setopt($curl, CURLINFO_HEADER_OUT, true); // 启用时追踪句柄的请求字符串。
	    $meta = curl_getinfo($curl);
	    // 运行curl
	    $data = curl_exec($curl);
	    curl_close($curl);
	    return $data;
	}

	/*
	* 保存抓取图片
	* $file 	string 抓取的图片
	* return 	string
	*/
	public function saveAsImage($file)
	{
	  	$fullpath = "D:/".uniqid().'.png';
	    $resource = fopen($fullpath, 'a');
	    fwrite($resource, $file);
	    fclose($resource);
	    return $fullpath;
	}
}
?>